#!/bin/bash

# 获取脚本所在目录，并切换到该目录
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
cd "$SCRIPT_DIR" || exit 1

# 检查当前目录是否是 Git 仓库
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
    echo "Error: Current directory is not a Git repository."
    read -p "Press Enter to exit..."
    exit 1
fi

# 检查 deploy_key 文件是否存在
if [ ! -f "deploy_key" ]; then
    echo "Error: deploy_key file not found in current directory."
    read -p "Press Enter to exit..."
    exit 1
fi

# 设置私钥权限为 600（仅当前用户可读）
chmod 600 deploy_key

# 获取远程仓库 URL
remote_url=$(git config --get remote.origin.url)

echo "Using deploy_key to fetch latest code from remote repository..."
echo "Remote repository: $remote_url"
echo "Warning: This will overwrite all local changes to tracked files (untracked files remain)."

# 使用 SSH 私钥强制拉取最新代码
GIT_SSH_COMMAND="ssh -i deploy_key -o IdentitiesOnly=yes -o StrictHostKeyChecking=no" git fetch --all

# 重置本地更改（仅跟踪的文件）
git reset --hard HEAD

# 强制同步到远程分支
current_branch=$(git symbolic-ref --short HEAD)
git reset --hard "origin/$current_branch"

echo "Operation completed. Local tracked files are now up-to-date with the remote."
echo "Note: Untracked files (e.g., .env) were not modified."
read -p "Press Enter to exit..."